# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.vm.box = "generic/ubuntu2204"
  config.vm.box_check_update = true
  config.vm.define "<VM NAME>"
  config.vm.hostname = "<VM NAME>"
  # allows us to ssh into the machine, addressing the problem below
  # https://www.reddit.com/r/vagrant/comments/sb7hfl/new_to_vagrant_getting_efault_warning/
  config.ssh.username = "vagrant"
  config.ssh.password = "vagrant"

  config.vm.provider "libvirt" do |vb|
    # Customize the amount of cpus and memory on the VM:
    vb.cpus = "4".to_i
    vb.memory = "16384".to_i
  end

  # sets up vm
  config.vm.provision :shell, path: "provision_root.sh"
  config.vm.provision :shell, privileged: false, path: "provision_nonroot.sh"
  # To ensure we don't run out of memory, we enable dynamic Swap Space. This is
  # done via the "swapspace" daemon: https://pqxx.org/development/swapspace/
  config.vm.provision :shell, inline: "sudo apt install swapspace -y"
  # The provision_root.sh adds the vagrant user to the docker group, so we need to reload the VM.
  config.vm.provision :reload
  config.vm.provision :shell, run: 'always', inline: <<-SHELL
    # When running gem5 in SE mode we must overcommit memory.
    # This is run on every startup of the VM.
    /sbin/sysctl vm.overcommit_memory=1
  SHELL
  config.vm.provision :shell, privileged: false, run: 'always', inline: <<-SHELL
    if [ -d ~/actions-runner ]; then
        # This will be run everytime the VM is run (once created).
        cd actions-runner
        nohup ./run.sh &
    else
        # This will be run the first time the VM is created.
        mkdir ~/actions-runner && cd ~/actions-runner
        curl -so actions-runner-linux-x64-2.304.0.tar.gz -L \
            https://github.com/actions/runner/releases/download/v2.304.0/actions-runner-linux-x64-2.304.0.tar.gz
        tar xzf ./actions-runner-linux-x64-2.304.0.tar.gz

        # configure the runner
        # echo automatically sets the name of the runner, and the tags
        # create a personal access token with admin permission and copy it into the curl command
        echo -ne '\n\nbuild\n\n' | ./config.sh --url https://github.com/<GITHUB REPO> --token $(curl -L \
            -X POST   -H "Accept: application/vnd.github+json"   -H "Authorization: Bearer <PERSONAL ACCESS TOKEN>" \
            -H "X-GitHub-Api-Version: 2022-11-28" \
           https://api.github.com/repos/<GITHUB REPO>/actions/runners/registration-token | jq -r '.token')
        # start the runner
        nohup ./run.sh &
    fi
  SHELL

end
